// 启动入口

using PEUtils;
using UnityEngine;
using System.Collections.Generic;
using ShawnNav;
using System;

public class Launcher : MonoBehaviour
{
    public bool isUseClick = false;

    NavConfig config;
    NavMap map;

    void Start()
    {
        PELog.InitSettings(LoggerType.Unity);
        // PELog.LogGreen("Init PELog Done.");

        LoadNavConfigFromMap();

        // 表现更新初始化
        NavView navView = GetComponent<NavView>();
        if (navView != null)
        {
            navView.verticeArr = config.verticeArr;
            NavMap.ShowAreaIDViewEvent = navView.ShowAreaIDView;
            NavMap.ShowPathViewEvent = navView.ShowPathView;
            NavMap.ShowConnerViewEvent = navView.ShowConnerView; 
        }
        map = new NavMap(config.indexArrList, config.verticeArr);
    }

    NavVector3 startPos = NavVector3.Zero;
    NavVector3 endPos = NavVector3.Zero;

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out RaycastHit hit, 1000))
            {
                Transform start = GameObject.FindGameObjectWithTag("Start").transform;
                if (isUseClick)
                    start.position = hit.point;
                
                startPos = new NavVector3(start.position.x, start.position.y, start.position.z);
            }
        }

        if (Input.GetMouseButtonDown(1))
        {
            if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out RaycastHit hit, 1000))
            {
                Transform target = GameObject.FindGameObjectWithTag("Target").transform;
                if (isUseClick)
                    target.position = hit.point;

                endPos = new NavVector3(target.position.x, target.position.y, target.position.z);
           
                if (startPos != endPos)
                {
                    map.CalcNavPath(startPos, endPos);
                }
            }
        }

        if (Input.GetKeyDown(KeyCode.T))
        {
            autoTest = !autoTest;
        }
        if (autoTest)
        {
            NavVector3 p1 = GetRandPos();
            NavVector3 p2 = GetRandPos();
            List<NavVector3> connerLst = map.CalcNavPath(p1, p2);
            if (connerLst?.Count > 0)
            {
                NavVector3 v1, v2;
                v1 = connerLst[0];
                for (int i = 1; i <connerLst.Count; i++)
                {
                    v2 = connerLst[i];
                    NavVector3 center = (v1 + v2) / 2.0f;
                    int areaID = map.GetAreaIDByPos(center);
                    if (areaID == -1)
                    {
                        string info = "";
                        for (int k = 0; k < connerLst.Count; k++)
                        {
                            info += $"{connerLst[k]}";
                        }

                        GameObject go = new GameObject();
                        go.name = center.ToString();
                        go.transform.position = new Vector3(center.x, center.y, center.z);
                        this.LogCyan($": {p1} to {p2} center: {center} posLst: {info}");
                        break;
                    }

                    v1 = v2;
                }
            }
        }
    }

    [Header("开启自动测试")]
    public bool autoTest = false;

    NavVector3 GetRandPos()
    {
        while (true)
        {
            System.Random rd = new System.Random();
            float x = rd.Next(0, 100);
            float z = rd.Next(0, 100);
            NavVector3 randPos = new NavVector3(x, 0, z);
            int areaID = map.GetAreaIDByPos(randPos);
            if (areaID != -1)
            {
                return randPos ;
            }
        }
    }



    [Header("调试线条颜色")]
    public Color wireColor = Color.black;
    
    private void OnDrawGizmos()
    {
        if (!Application.isPlaying || config == null)
        {
            LoadNavConfigFromMap();
        }

        if (config == null) return;

        Gizmos.color = wireColor;
        for (int i = 0; i < config.indexArrList.Count; i++)
        {
            int[] indexArr = config.indexArrList[i];
            Vector3 v1, v2;
            int count = indexArr.Length;
            for (int j = 0, k = count - 1; j < count; k = j++)
            {
                NavVector3 nv1 = config.verticeArr[indexArr[k]];
                NavVector3 nv2 = config.verticeArr[indexArr[j]];
                v1 = new Vector3(nv1.x, nv1.y, nv1.z);
                v2 = new Vector3(nv2.x, nv2.y, nv2.z);
                Gizmos.DrawLine(v1, v2);
            }
        }

        Gizmos.color = Color.white;
    }

    /// <summary>
    /// 根据场景命名规则将 点与面 的信息存储到配置数据config中
    /// </summary>
    void LoadNavConfigFromMap()
    {
        GameObject map = GameObject.FindGameObjectWithTag("mapRoot");

        if (map == null) return;

        Transform pointTrans = map.transform.Find("pointRoot");
        Transform indexTrans = map.transform.Find("indexRoot");

        config = new NavConfig
        {
            indexArrList = new List<int[]>(),
            verticeArr = new NavVector3[pointTrans.childCount]
        };


        for (int i = 0; i < indexTrans.childCount; i++)
        {
            Transform trans = indexTrans.GetChild(i);
            
            if (!trans.gameObject.activeSelf)
                continue;

            string[] indexStrArr = trans.name.Split('-');
            int[] indexArr = new int[indexStrArr.Length];
            for (int j = 0; j < indexStrArr.Length; j++)
            {
                indexArr[j] = int.Parse(indexStrArr[j]);
            }
            config.indexArrList.Add(indexArr);
        }
        NavVector3[] verticeArr = new NavVector3[pointTrans.childCount];

        for (int i = 0; i < pointTrans.childCount; i++)
        {
            Transform point = pointTrans.GetChild(i);
            verticeArr[i] = new NavVector3(point.position.x, point.position.y, point.position.z);
        }
        config.verticeArr = verticeArr;
    }
}